
const db = require('../../model/gpwsDev');
const FastInfo = db.FastInfo;
const TopInfo = db.TopInfo;
const UserType = db.UserType;
const redisService = require('../redis');
const _ = require('lodash');
const Promise = require('bluebird');


/**
 * 获取单个排名靠前的头条
 * @param par
 * @param options
 */
function getOneTopInfo(par, options) {
    return TopInfo.findOne(par.where, par.fields, options).exec()
}

/**
 * 获取一批topinfo的数据
 * @param par
 * @param options
 */
function getManyTopInfos(par, options) {
    return TopInfo.find(par.where, par.fields, options).exec()
}

/**
 * 根据涨跌进行一个股票排序
 * @param topInfo
 */
function sortStockByZhangDie(topInfo) {
    let stocks = topInfo.stocks;
    let eCodes = _.map(stocks, 'eCode');
    return redisService.getZhangDieByECodes(eCodes).then(scores => {
        _.each(scores, (score, i) => {
            stocks[i].zhangFu = score ? parseFloat(score) : -11;
        });
        topInfo.stocks = _.sortBy(stocks, stock => {
            return -stock.zhangFu;
        });
    }).then(() => {
        return Promise.resolve()
    }).catch(e => {
        return Promise.reject(e);
    });
}

/**
 * 查询快讯内容
 * @param par (where: 查询条件)
 * @param options
 * options: 其他条件
 */
function getAllFastInfo(par, options) {
    return FastInfo.find(par.where, par.fields, options)
}

/**
 * 获取快讯的作者根据Id
 * @param par
 */
function getFastAuthor(par) {

    return UserType.find({_id: par}).exec()
        .then((data)=> {
            return _.keyBy(data, (item)=> item._id);
        })
}

module.exports = {
    //  获取单个排行信息
    getTopInfo: getOneTopInfo,
    //  批量获取排行信息
    getManyTopInfos: getManyTopInfos,
    //  根据涨跌进行股票排序
    sortStockByZhangDie: sortStockByZhangDie,
    //  批量获取快讯内容
    getAllFastInfo: getAllFastInfo,
    //  获取快讯的作者信息
    getFastAuthor: getFastAuthor
};